//
//  CZPhotoSelectorViewController.swift
//  30.照片选择器-UI搭建
//
//  Created by Apple on 15/12/7.
//  Copyright © 2015年 wdd. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class CZPhotoSelectorViewController: UICollectionViewController {
    
    // MARK: - 属性
    /// 用户选择的照片数组
    var photos = [UIImage]()
    
    private let MAXPhotoCount = 6
    
    /// 当前点击的cell的indexPath
    private var currentIndexPath: NSIndexPath?
    
    private var layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(collectionViewLayout: layout)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        collectionView?.backgroundColor = UIColor.whiteColor()
        
        prepareLayout()
    }
    
    private func prepareLayout() {
        // 注册cell
        self.collectionView!.registerClass(CZPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // 设置layout
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 当图片数量小于最大张数时,显示图片数量+1 个cell
        // 当图片数量等于最大张数时,显示最大张数(图片数量)
        return photos.count < MAXPhotoCount ? photos.count + 1 : MAXPhotoCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CZPhotoSelectorCell
        
        // 设置控制器称为代理
        cell.cellDelegate = self
        
        // 可以取到图片,才设置图片
        if indexPath.item < photos.count {
            cell.image = photos[indexPath.item]
        } else {
            // 最后一个没有图片,设置加号图片
            cell.setAddButton()
        }
    
        return cell
    }
}

// MARK: - 扩展 CZPhotoSelectorViewController 实现 CZPhotoSelectorCellDelegate 代理
extension CZPhotoSelectorViewController: CZPhotoSelectorCellDelegate {
    /// 加号按钮点击
    func photoSelectorCellAddButtonClick(cell: CZPhotoSelectorCell) {
        // 弹出系统的照片库
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("无法访问照片库")
            return
        }
        
        // 记录下被点击的cell indexPath
        currentIndexPath = collectionView!.indexPathForCell(cell)!
        
        let pickController = UIImagePickerController()
        
        // 需要获取用户选择的照片必须成为pickController的代理.
        pickController.delegate = self
        
        presentViewController(pickController, animated: true, completion: nil)
    }
    
    /// 删除按钮点击
    func photoSelectorCellRemoveButtonClick(cell: CZPhotoSelectorCell) {
        print("删除按钮点击")
        
        // 获取到点击cell的indexPath
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        // 去photos数组里面删除对应的图片
        photos.removeAtIndex(indexPath.item)
        
        collectionView?.reloadData()
    }
}

// MARK: - 扩展 CZPhotoSelectorViewController 实现 UIImagePickerControllerDelegate, UINavigationControllerDelegate 代理
extension CZPhotoSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 通过这个方法来获取用户选择的图片
    // 一旦实现这个代理方法,需要手动关闭控制器
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print("选择图片: \(image)")
        
        // 缩放图片
        let newImage = image.scaleImage()
        print("缩放后的图片: \(newImage)")
        
        // 判断点击的是图片还是加号按钮
        // currentIndexPath.item = photos.count 点击的就是最后一个
        if currentIndexPath!.item == photos.count {
            // 点击的是加号按钮
            // 将用户选择的图片添加到数组
            photos.append(newImage)
        } else{
            // 点击的是图片,替换对应的图片
            photos[currentIndexPath!.item] = newImage
        }
        
        // 刷新
        collectionView?.reloadData()
        
        // picker刚才弹出的系统照片库
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - cell点击的协议
@objc protocol CZPhotoSelectorCellDelegate: NSObjectProtocol {
    // 默认:代理方法必须实现
    // optional表示可选
    
    /// 加号按钮点击
    optional func photoSelectorCellAddButtonClick(cell: CZPhotoSelectorCell)
    
    /// 删除按钮点击
    optional func photoSelectorCellRemoveButtonClick(cell: CZPhotoSelectorCell)
}

// MARK: - 自定义cell
class CZPhotoSelectorCell: UICollectionViewCell {
    
    // MARK: - 按钮点击事件
    /// 显示的图片
    var image: UIImage? {
        didSet {
            // 将图片设置到按钮上面显示
            addButton.setImage(image, forState: UIControlState.Normal)
            
            // 显示删除按钮
            removeButton.hidden = false
        }
    }
    
    /// 代理属性
    weak var cellDelegate: CZPhotoSelectorCellDelegate?
    
    /// 加号按钮点击
    func addButtonClick() {
        // photoSelectorCellAddButtonClick: 方法是可选的,代理对象可能实现,也可能没有实现
        // photoSelectorCellAddButtonClick?: 如果代理实现这个方法就调用这个方法,如果代理没有实现这个方法,就不调用
        cellDelegate?.photoSelectorCellAddButtonClick?(self)
    }
    
    /// 删除按钮点击
    func removeButtonClick() {
        cellDelegate?.photoSelectorCellRemoveButtonClick?(self)
    }
    
    /// 设置cell的addButton的图片为加号图片
    func setAddButton() {
        // 设置图片
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        // 隐藏删除按钮
        removeButton.hidden = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }

    // MARK: - 准备UI
    private func prepareUI() {
        // 添加子控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        // 添加约束
        addButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        let views = ["ab": addButton, "rb": removeButton]
        // VFL
        // addButton 填充父控件
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        // removeButton 父控件右上角
        // 水平: 在父控件的右边
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        // 垂直:在父控件顶部
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
    }
    
    // MARK: - 懒加载
    /// 加号按钮,显示用户选择的图片
    private lazy var addButton: UIButton = {
        let button = UIButton()
        
        // 设置图片
//        button.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        // 添加点击事件
        button.addTarget(self, action: "addButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        return button
    }()
    
    /// 删除按钮
    private lazy var removeButton: UIButton = {
        let button = UIButton()
        
        // 设置图片
        button.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        // 添加点击事件
        button.addTarget(self, action: "removeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}